package com.notebad.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.notebad.GeneralVariables;
import com.notebad.R;
import com.notebad.note.Note;
import com.notebad.note.NotesDbManager;
import com.notebad.tools.FileUtilities;

public class NoteListView extends ListActivity {

	@SuppressWarnings("unused")
	private static final String TAG = "[NoteListView]";
	
	private static final String DEFAULT_CAT = "Tout";

	private static final int NEW_NOTE_ID = Menu.FIRST;
	private static final int NEW_NOTE_ECRITE = 0;
	private static final int NEW_NOTE_PHOTO = 1;
	private static final int NEW_NOTE_SON = 2;

	private NotesDbManager mDbHelper;
	private EditText mSearchField;
	private ImageView imageView;
	private Spinner mCategText;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notes_list);
		imageView = (ImageView) findViewById(R.id.searchLogo);
		imageView.setImageResource(R.drawable.ic_menu_search);
		mCategText = (Spinner) findViewById(R.id.categorySpinner);
		mDbHelper = new NotesDbManager(this);
		
		this.fillSpinner();

		mSearchField = (EditText) findViewById(R.id.searchField);
		mSearchField.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable arg0) {
				fillData(mSearchField.getText().toString());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
		});
		
		mCategText.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				fillData(mSearchField.getText().toString());
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int index, final long arg3) {
				AlertDialog.Builder builder = new AlertDialog.Builder(NoteListView.this);
				builder.setMessage("Supprimer cette note ?")
				.setCancelable(false)
				.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						deleteNote(arg3);
						fillData(mSearchField.getText().toString());
					}
				})
				.setNegativeButton("Non", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}
		});
	}

	
	private void fillSpinner()
	{
		mDbHelper.open();
		Cursor curs= mDbHelper.getCategories();
		startManagingCursor(curs);

		List<String> cate = new ArrayList<String>();
		if (curs != null) {
			while(curs.moveToNext()){
				cate.add(curs.getString(curs.getColumnIndexOrThrow(NotesDbManager.KEY_CAT_NAME)));
			}
		}
		if (curs != null)
			curs.close();

		ArrayAdapter<CharSequence> m_adapterForSpinner = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);        
		m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mCategText.setAdapter(m_adapterForSpinner);
		m_adapterForSpinner.add(DEFAULT_CAT);
		for (String string : cate) {
			m_adapterForSpinner.add(string);
		}
		mDbHelper.close();
	}

	
	private void fillData(String filter) {
		mDbHelper.open();
		
		if(filter == null)
			filter = "";
		
		if(mCategText.getCount() != 0 && filter.equals(""))
		{
			if(mCategText.getSelectedItem() == null)
				filter = (String) mCategText.getItemAtPosition(0);
			else
			{
				if(!((String) mCategText.getSelectedItem()).equals(DEFAULT_CAT))
					filter = (String) mCategText.getSelectedItem();
			}
		}
		else 
		{
			if(mCategText.getSelectedItem() == null)
				filter = filter + " " + (String) mCategText.getItemAtPosition(0);
			else
			{
				if(!((String) mCategText.getSelectedItem()).equals(DEFAULT_CAT))
					filter = filter + " " + (String) mCategText.getSelectedItem();
			}
		}
		
		String[] strings = filter.split(" ");
		Cursor notesCursor = mDbHelper.fetchAllNotes(strings);
		startManagingCursor(notesCursor);

		// Create an array to specify the fields we want to display in the list (TITLE, DATE and ADDRESS)
		String[] from = new String[]{NotesDbManager.KEY_TITLE, NotesDbManager.KEY_DATE, NotesDbManager.KEY_ADDRESS};

		// and an array of the fields we want to bind those fields to
		int[] to = new int[]{R.id.titre, R.id.date, R.id.adresse};

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
		setListAdapter(notes);
		mDbHelper.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
		fillData(mSearchField.getText().toString());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, NEW_NOTE_ID, 0, R.string.menu_add).setIcon(R.drawable.ic_menu_add);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case NEW_NOTE_ID:
			final CharSequence[] items = {"Texte", "Photo", "Son"};

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Type de note");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					Intent i;
					switch(item) {
					case NEW_NOTE_ECRITE :
						Note.initCurrentNote();
						i = new Intent(NoteListView.this, VisualisationView.class);
					    startActivity(i);
						break;
					case NEW_NOTE_PHOTO :
						Note.initCurrentNote();
						i = new Intent(NoteListView.this, CameraView.class);
						startActivity(i);
						break;
					case NEW_NOTE_SON :
						Note.initCurrentNote();
						i = new Intent(NoteListView.this, AudioRecorderView.class);
						startActivity(i);
						break;

					}
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	/**
	 * Delete note from database and memory with the given id
	 * 
	 * @param id
	 */
	private void deleteNote(long id)
	{
		mDbHelper.open();
		mDbHelper.deleteNote(id);
		mDbHelper.close();
		FileUtilities.deleteDirectory(new File(GeneralVariables.APLLICATION_FOLDER + File.separator + "Note" + id));
		fillData(mSearchField.getText().toString());
	}

	private void editNote(Note note) {
		Note.setCurrentNote(note);
		Intent i = new Intent(this, VisualisationView.class);
		startActivity(i);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		mDbHelper.open();
		editNote(mDbHelper.fetchNote(id));
		mDbHelper.close();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		fillData(mSearchField.getText().toString());
	}
}